package oop.ex3.usercommands;

import java.util.LinkedList;

import oop.ex3.filemanager.FileManager;
import oop.ex3.filemanager.UploadFile;
import oop.ex3.protocol.ContainFile;
import oop.ex3.protocol.DontContainFile;
import oop.ex3.sharedclasses.IPaddress;

public class Rename extends UserMessage {

	private String _oldName, _newName;
	public static final String COMMAND = "RENAME";
	
	//TODO check with school solution:
	/*
	 * if the first interaction between a FM an NS is rename,
	 * is it ok that the database sent @ begin will be already with the rename file?
	 */
	/**
	 * Constructs a new Rename userCommand.
	 * sets oldName as the command's old file name, and newName as the
	 * new name to be given to the file.
	 * @param fileManager the FileManager using this UserMessage.
	 * @param oldName the old file name.
	 * @param newName the new file name.
	 */
	public Rename(FileManager fileManager, String oldName, String newName) {
		super(fileManager);
		this._oldName=oldName;
		this._newName=newName;
	}

	//TODO don't forget to set file back to Uploadable after the process.
	@Override
	public boolean run() {
		UploadFile toBeRenamed=this._fileManager.contains(_oldName);
		// null -> file is not found in the FileManager.
		if (toBeRenamed==null){
			System.out.println("It is impossible to rename an absent file");
			return FAILURE;
		}
		if (this._fileManager.contains(_newName)!=null){
			System.out.println("It is illegal to use and existing file name as a new name");
			return FAILURE;
		}
		synchronized (toBeRenamed) {
			
			//TODO check if setNotUploadable is enough
			// Or the whole this needs to be synchronized
			toBeRenamed.setNotUploadable();
			this._fileManager.removeFromFileManager(_oldName);
			// by first removing from FileManager DB, FILENOTFOUND will be received
			// when asking for this file.
		}
		
		/*if (MyFileManager.finishUploading(this._fileManager ,toBeRemoved.getName())
				==SUCCESS){
			//Finished uploading the file;
		}*/
		//TODO ^ alternative,
		if (_fileManager.finishFileUpload(_oldName)){
			this._fileManager.rename(_oldName,_newName);
		}
		//Right now, toBeRemoved points to NULL!
		
		announceAllServers();
		System.out.println("Renaming Done");
		
		// TODO Auto-generated method stub
		return SUCCESS;
	}

	private void announceAllServers(){
		LinkedList<IPaddress> nameServers = _fileManager.getNameServerList();
		DontContainFile dontAnnouncer = new DontContainFile();
		for (IPaddress nameServer : nameServers){
			dontAnnouncer.runAsClient(_fileManager, nameServer, _oldName);
			//TODO check what happens after failure
		}
		ContainFile containAnnouncer = new ContainFile();
		for (IPaddress nameServer : nameServers){
			containAnnouncer.runAsClient(_fileManager, nameServer, _newName);
			//TODO check what happens after failure
		}
	}
}

